//
//  WBOAuthTableViewController.swift
//  Weibo
//
//  Created by xu on 2017/3/18.
//  Copyright © 2017年 xuantong. All rights reserved.
//

import UIKit

import SVProgressHUD

class WBOAuthTableViewController: UIViewController {
    
    
    //定义属性
    let webView = UIWebView()
    
    override func loadView() {
   
         //绑定根视图
        view = webView
        //指定代理
        webView.delegate = self;
        
    
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置隐藏底部的tar webview 上拉的时候会有底部栏黑框
        self.view.isOpaque = true
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title:"关闭", imageName: nil, target: self, action: #selector(click))
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title:"快速登录", imageName: nil, target: self, action: #selector(fillAccount))
        
        self.view.backgroundColor = UIColor.white
        
        //请求授权页面
        loadOauthPage()
        
    }
    

    //当界面即将消失的时候 -进行dismiss
    override func viewWillDisappear(_ animated: Bool) {
        
        SVProgressHUD.dismiss()
    }
    
    //请求授权页面方法
    private func loadOauthPage() {
     
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
       
        let url = URL(string: urlString)
      
        //2. req
        guard let u = url else {
            return
        }

        let req = URLRequest(url:u)
        
         webView.loadRequest(req)

    }
    
    
    @objc private func fillAccount() {
//        let jsString = "document.getElementById('userId').value = '15052839432', document.getElementById('passwd').value = 'xxxx123'"
        
         let jsString = "document.getElementById('userId').value = '18516018819', document.getElementById('passwd').value = '940725'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }

    
    
    @objc private func click(){
        dismiss(animated: true, completion: nil)
    }
    
    
  }


//将代理方法抽取到分类中实现, 将模块的功能独立出来,更加好维护

extension WBOAuthTableViewController: UIWebViewDelegate {
    
    //MARK:  实现web的代理方法
    //显示圈圈
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //隐藏
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //获取加载页面的url

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.url?.absoluteString ?? ""
        
        let flag = "code="
        
        if urlString.contains(flag) {
            
            //能够截取code
            let query = request.url?.query ?? ""
            
            let code = (query as NSString).substring(from: flag.characters.count)
            
            ////4. 通过code 请求token  -> 请求接口地址\
            WBUserAccountViewModel.shared.loadAccessToken(code: code, finished: { (success) in
                
                if !success {
                    //失败
                    SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没有网络")
                    return

                }
                 print("登录成功 跳转到欢迎页面")
                //请求成功使用通知来发送消息进行切换控制器
                // 发送通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: SWITCHROOTVIEWCONTROLLERNOTI), object: nil)
            })
            
    
            return false
            
        }
        
        return true
    }
    
  }



